package com.qiumo.gmtool.utils;

import cn.hutool.core.io.file.FileReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiumo.gmtool.GmToolApplication;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import lombok.var;

public final class FileUtils {

    public static byte[] readResource(String resourcePath) {
        try (InputStream is = GmToolApplication.class.getResourceAsStream(resourcePath)) {
            return readBytes(is);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return new byte[0];
    }

    public static JSONObject readJson(String path) {
        try (InputStream inputStream = new FileInputStream(path)) {
            JSONObject json = JSON.parseObject(inputStream,JSONObject.class);
            return json;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static JSONArray readJsonArray(String path) {
        try {
            FileReader fileReader = new FileReader(path);
            String result = fileReader.readString();
            JSONArray json = JSONArray.parseArray(result);
            return json;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static byte[] readBytes(InputStream inputStream) {
        try {
            var byteArrayOutputStream = new ByteArrayOutputStream();
            int _byte;
            while ((_byte = inputStream.read()) != -1) {
                byteArrayOutputStream.write(_byte);
            }
            var result = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            inputStream.close();
            return result;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

